package com.ziyun.pop.modules.storeMaterials.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.utility.New;
import com.ziyun.pop.common.e.DeleteEnum;
import com.ziyun.pop.common.e.material.DirectionEnum;
import com.ziyun.pop.common.e.material.StockMaterialIoTypeEnum;
import com.ziyun.pop.common.e.material.StoreMaterialInStatusEnum;
import com.ziyun.pop.common.e.storematerialin.StorePurchaseApplyDetailEnum;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.erpStockLog.entity.ErpStockLogEntity;
import com.ziyun.pop.modules.erpStockLog.service.ErpStockLogService;
import com.ziyun.pop.modules.purchase.entity.StorePurchaseApplyDetailEntity;
import com.ziyun.pop.modules.purchase.entity.StorePurchaseApplyEntity;
import com.ziyun.pop.modules.purchase.entity.dto.StorePurchaseApplyDto;
import com.ziyun.pop.modules.purchase.entity.dto.storePurchaseAutoDto;
import com.ziyun.pop.modules.storeMaterials.dao.StoreMaterialInDao;
import com.ziyun.pop.modules.storeMaterials.entity.*;
import com.ziyun.pop.modules.storeMaterials.entity.dto.StoreMaterialInDto;
import com.ziyun.pop.modules.storeMaterials.entity.vo.StoreMaterialInDetailVo;
import com.ziyun.pop.modules.storeMaterials.service.*;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import net.bytebuddy.implementation.bytecode.Throw;
import io.renren.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;

import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;

@Service("storeMaterialInService")
public class StoreMaterialInServiceImpl extends ServiceImpl<StoreMaterialInDao, StoreMaterialInEntity> implements StoreMaterialInService {
	@Autowired
	private StoreMaterialInDetailService storeMaterialInDetailService;
	@Autowired
	private StoreStockMaterialService storeStockMaterialService;
	@Autowired
	private StoreStockMaterialIoService storeStockMaterialIoService;
	@Autowired
	private StoreMaterialInService storeMaterialInService;
	@Autowired
	private StorePurchaseApplyDetailService storePurchaseApplyDetailService;
	@Autowired
	private MaterialService materialService;
	@Autowired
	private ErpStockLogService erpStockLogService;
	@Autowired
	private StoreMaterialOutDetailService storeMaterialOutDetailService;



	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String inNo = StringUtil.getRequestParamString(params.get("inNo"));
		Page<StoreMaterialInEntity> page = (Page<StoreMaterialInEntity>) this.page(
				new Query<StoreMaterialInEntity>(params).getPage(),
				new QueryWrapper<StoreMaterialInEntity>()
						.eq(StringUtil.isNotEmpty(inNo), "in_no", inNo).eq("stock_id",params.get("stockId"))
		);
		return new PageUtils(page);
	}

	/**
	 * 查询入库信息
	 *
	 * @param params
	 * @return
	 */
	@Override
	public R queryInDetial(Map<String, Object> params) {
		// 入库类型
		Integer type = StringUtil.getRequestParamInteger(params.get("type"));
		// 入库单号
		String inNo = StringUtil.getRequestParamString(params.get("inNo"));
		if (type == null) {
			return R.error("未选择入库类型！");
		} else if (StringUtil.isNull(inNo)) {
			return R.error("未输入单据号！");
		} else if (type.intValue() == StockMaterialIoTypeEnum.PUCHASE_IN.toInt()) { // 采购入库
			List<StoreMaterialInDetailVo> materiallist = baseMapper.selectPurchaseApplyDetail(inNo);
			// 带出采购备注和审核备注
			Map<String,String> remarks  =  this.baseMapper.getStorePurchaseApplyByInNo(inNo);
			if (materiallist.size() == 0) {
				return R.error("请保证单据号已审批！");
			} else {
				return R.ok().put("materiallist", materiallist).put("remarks",remarks);
			}
		} else if (type.intValue() == StockMaterialIoTypeEnum.ALLOT_IN.toInt()) { // 调拨入库
			List<StoreMaterialInEntity> storeMaterialInList = baseMapper.getStoreMaterialInList(inNo);
			if (storeMaterialInList.size()>0){
				return R.error("该单号已经入库,不能再入库");
			}
			List<StoreMaterialOutDetailEntity> materiallist = baseMapper.sleectStoreOutDetail(inNo);
			Map<String,String> remarks  =  baseMapper.getOutMarks(inNo);
			if (materiallist.size() == 0) {
				return R.error("请保证单据号已审批！");
			} else {
				return R.ok().put("materiallist", materiallist).put("remarks",remarks);
			}
		} else if (type.intValue() == StockMaterialIoTypeEnum.COUNTERACT.toInt()) { // 红冲
			List<StoreMaterialInEntity> status = null;
			try {
				status = baseMapper.getStatus(inNo);
			} catch (Exception e) {
				throw new RuntimeException("请保证对应单据号已经入库");
			}
			if(status.size()!=0){
				List<storePurchaseAutoDto> materiallist = baseMapper.sleectStoreOutDetailByApply(inNo);
				return R.ok().put("materiallist", materiallist);
			}else{
				return R.error("未获取到数据！");
			}
		}
		return R.error("未获取到数据！");
	}

	/**
	 * 入库信息保存
	 *
	 * @param storeMaterialInDto
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveIn(StoreMaterialInDto storeMaterialInDto) {
		/*入库信息*/
		StoreMaterialInEntity storeMaterialInEntity = storeMaterialInDto.getStoreMaterialInEntity();
		Integer type = storeMaterialInEntity.getType();
		if(type == null){
			return R.error("请输入正确的入库单号");
		}
		if (type.intValue() == StockMaterialIoTypeEnum.PUCHASE_IN.toInt()) {
			String applyNo = storeMaterialInEntity.getInNo();
			List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList1 = storeMaterialInDto.getStoreMaterialInDetailEntityList();
			if(storeMaterialInDetailEntityList1 == null){
				return R.error("请输入完单据号查询出要入库的明细再确认入库");
			}
			for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntityList1) {
				if (storeMaterialInDetailEntity.getMaterialQuantity().compareTo(storeMaterialInDetailEntity.getQuantity()) == 1) {
					return R.error("耗材ID：" + storeMaterialInDetailEntity.getMaterialId() + " 入库数量不能大于申请数量");
				}
			}
			BigDecimal MaxQuantity = null;
			String materialId;
			//  这里应该获取采购申请的明细
			List<StorePurchaseApplyDetailEntity> storePurchaseApplyDetailByApplyNo = storePurchaseApplyDetailService.getStorePurchaseApplyDetailByApplyNo(applyNo);
			if (storePurchaseApplyDetailByApplyNo.size() != 0) {
				// 获取单据号下的物料总价
				BigDecimal StorematerialInEntityTotalMoney = null;
				String materialId1 ;
				BigDecimal materialQuantity;
				BigDecimal receiveQuantity;
				String inNo;
				int count = 1;
				for(int i = 0;i<storeMaterialInDetailEntityList1.size();i++){
					materialId1 = storeMaterialInDetailEntityList1.get(i).getMaterialId();
					inNo = storeMaterialInEntity.getInNo();
					materialQuantity = storePurchaseApplyDetailService.getMaterialQuantity(inNo, materialId1);
					receiveQuantity = storePurchaseApplyDetailService.getReceiveQuantity(inNo,materialId1);
					BigDecimal EndQuantity = materialQuantity.subtract(receiveQuantity);
					if(i == 0 && materialQuantity.compareTo(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity()) == 0){
						StorematerialInEntityTotalMoney = storePurchaseApplyDetailByApplyNo.get(i).getTotalMoney();
					}else if (i > 0 && materialQuantity.compareTo(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity()) == 0){
						StorematerialInEntityTotalMoney = StorematerialInEntityTotalMoney.add(storePurchaseApplyDetailByApplyNo.get(i).getTotalMoney());
					}else if(i == 0 && EndQuantity.compareTo(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity()) == 1){
						StorematerialInEntityTotalMoney = storeMaterialInDetailEntityList1.get(i).getUnitMoney().multiply(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity());
					}else if(i > 0 && EndQuantity.compareTo(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity()) == 1){
						StorematerialInEntityTotalMoney = StorematerialInEntityTotalMoney.add(storeMaterialInDetailEntityList1.get(i).getUnitMoney().multiply(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity()));
					}else if(i == 0 || i > 0 && EndQuantity.compareTo(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity()) == 0){
						// 申请的总金额
						BigDecimal totalMoney = storePurchaseApplyDetailService.getTotalMoney(inNo);
						// 查询已经入库并且审核的
						List<StoreMaterialInEntity> alreadyInAndState = storeMaterialInService.getAlreadyInAndState(inNo);
						for(int a = 0;a<alreadyInAndState.size();a++){
							if (a == 0){
								StorematerialInEntityTotalMoney	= totalMoney.subtract(alreadyInAndState.get(a).getTotalMoney());
							}else{
								StorematerialInEntityTotalMoney = StorematerialInEntityTotalMoney.subtract(alreadyInAndState.get(a).getTotalMoney());
							}
						}
						i = storeMaterialInDetailEntityList1.size()-1;
					}
				}
				for (StoreMaterialInDetailEntity storeMaterialInDetailEntity1 : storeMaterialInDetailEntityList1) {
					materialId = storeMaterialInDetailEntity1.getMaterialId();
					//  查询当前入库的已经使用了多少MaterialQuantity
						MaxQuantity = storePurchaseApplyDetailService.getReceiveQuantity(applyNo, materialId);
						// 声明一个变量用来接收最后还有多少可以使用的
						BigDecimal EndQuantity = null;
						//  总共的减去已经入库的 得到还有多少没有入库的
						EndQuantity = storeMaterialInDetailEntity1.getQuantity().subtract(MaxQuantity);
						if (EndQuantity.compareTo(storeMaterialInDetailEntity1.getMaterialQuantity()) == -1) {
							return R.error("耗材ID：" + storeMaterialInDetailEntity1.getMaterialId() + "的入库数量不能大于采购申请部分入库后的数量");
						}
						storeMaterialInEntity.setDirection(1);
						storeMaterialInEntity.setCreateName(UserUtils.getCurentUser().getUsername());
						ErpStockEntity stockEntity = baseMapper.getStockBySellerId(UserUtils.getCurentUser().getSellerId(), 1);
						storeMaterialInEntity.setStockId(stockEntity.getStockId());
						// 仓库
						ErpStockEntity stockBySellerId = baseMapper.getStockBySellerId(UserUtils.getCurentUser().getSellerId(), 1);
						storeMaterialInDetailEntity1.setInId(stockBySellerId.getStockId());
						storeMaterialInDetailEntity1.setInNo(storeMaterialInEntity.getInNo());
						storeMaterialInDetailEntity1.setMaterialQuantity(storeMaterialInDetailEntity1.getMaterialQuantity());
						storeMaterialInDetailEntity1.setTotalMoney(storeMaterialInDetailEntity1.getMaterialQuantity().multiply(storeMaterialInDetailEntity1.getUnitMoney()));
						storeMaterialInEntity.setTotalMoney(StorematerialInEntityTotalMoney);
						if(count == 1){
							baseMapper.insert(storeMaterialInEntity);
							count ++;
						}
					storeMaterialInDetailService.saveListByCG(storeMaterialInDetailEntity1, storeMaterialInEntity);
				}

				ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
				erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
				erpStockLogEntity.setLogText("采购入库保存操作");
				erpStockLogEntity.setType(1);
				erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
				erpStockLogService.saveBatch(erpStockLogEntity);
				return R.ok();
			} else{
				return R.error("采购申请请选择要申请的对应物料信息");
			}
		}else if (type.intValue() == StockMaterialIoTypeEnum.ALLOT_IN.toInt()) {
			BigDecimal MaxQuantity = null;
			String materialId;
			String applyNo = storeMaterialInEntity.getInNo();
			List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = storeMaterialInDto.getStoreMaterialInDetailEntityList();
			// 获取单据号下的物料总价
			BigDecimal StorematerialInEntityTotalMoney = null;
			for (int i = 0; i < storeMaterialInDetailEntityList.size(); i++) {
				if(i == 0){
					StorematerialInEntityTotalMoney = storeMaterialInDetailEntityList.get(i).getUnitMoney().multiply(storeMaterialInDetailEntityList.get(i).getMaterialQuantity());
				}else{
					StorematerialInEntityTotalMoney = storeMaterialInDetailEntityList.get(i).getUnitMoney().multiply(storeMaterialInDetailEntityList.get(i).getMaterialQuantity()).add(StorematerialInEntityTotalMoney);
				}
			}
			for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntityList) {
				materialId = storeMaterialInDetailEntity.getMaterialId();
				// 这个地方就去查询出库明细的多少个
				MaxQuantity = storeMaterialOutDetailService.getMaterialQuantityByMaterialId(materialId, applyNo);
				if (storeMaterialInDetailEntity.getMaterialQuantity().compareTo(BigDecimal.ZERO) == 0) {

					return R.error("耗材ID：" + storeMaterialInDetailEntity.getMaterialId() + " 的入库数量不能为0!");
				}

				if (storeMaterialInDetailEntity.getMaterialQuantity().compareTo(MaxQuantity) == 1) {
					return R.error("耗材ID：" + storeMaterialInDetailEntity.getMaterialId() + " 的入库数量不能大于出库总数量!");
				}

				if(storeMaterialInDetailEntity.getSupplierId() == null){
					return R.error("耗材ID：" + storeMaterialInDetailEntity.getMaterialId() + " 的供应商不能为空");
				}

				storeMaterialInEntity.setDirection(1);
				storeMaterialInEntity.setCreateName(UserUtils.getCurentUser().getUsername());
				ErpStockEntity stockEntity = baseMapper.getStockBySellerId(UserUtils.getCurentUser().getSellerId(), 1);
				storeMaterialInEntity.setStockId(stockEntity.getStockId());
				storeMaterialInDetailEntity.setTotalMoney(storeMaterialInDetailEntity.getUnitMoney().multiply(storeMaterialInDetailEntity.getMaterialQuantity()));
			}
			storeMaterialInEntity.setTotalMoney(StorematerialInEntityTotalMoney);
			baseMapper.insert(storeMaterialInEntity);
			storeMaterialInDetailService.saveList(storeMaterialInDetailEntityList,storeMaterialInEntity);
			ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
			erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
			erpStockLogEntity.setLogText("调拨入库保存操作");
			erpStockLogEntity.setType(2);
			erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
			erpStockLogService.saveBatch(erpStockLogEntity);
			return R.ok();
		} else if (type.intValue() == StockMaterialIoTypeEnum.COUNTERACT.toInt()) {
			StoreStockMaterialIoEntity storeStockMaterialIoEntity = new StoreStockMaterialIoEntity();
			String inNo = storeMaterialInEntity.getInNo();
			Integer EnumType = StockMaterialIoTypeEnum.PUCHASE_IN.toInt();

			Integer EnumTypes = StockMaterialIoTypeEnum.COUNTERACT.toInt();
			// 这里要先判断是否有红冲记录
			String oldInNo = inNo+"-%";
			List<StoreMaterialInEntity> storeMaterialInEntitiesSix = storeMaterialInService.getStoreMaterialListByEnumTypes(oldInNo,EnumTypes);
			if(storeMaterialInEntitiesSix.size() == 0){
				StoreMaterialInDetailEntity storeMaterialInDetailEntityes = new StoreMaterialInDetailEntity();
				// 这里只是查询已经审核并且是采购入库的的把它冲红掉
				List<StoreMaterialInEntity> storeMaterialInEntities = storeMaterialInService.getStoreMaterialListByState(inNo,EnumType);
				if (storeMaterialInEntities.size() != 0) {
					//这个是查询出同一个采购入库单分批入库的所有单号
					Integer stockId = null;
					for (StoreMaterialInEntity materialInEntity : storeMaterialInEntities) {
						Integer inId = materialInEntity.getInId();
						stockId = materialInEntity.getStockId();
						// 这个是遍历出一个单号下面的所有物料信息
						List<StoreMaterialInDetailEntity> storeMaterialInDetailEntities = storeMaterialInDetailService.getInid(inId);
						for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntities) {
							String materialId = storeMaterialInDetailEntity.getMaterialId();
							// 入库数量
							BigDecimal quantity = storeMaterialInDetailEntity.getMaterialQuantity();
							// 获取对应的单价
							BigDecimal cost = storeStockMaterialService.getCost(materialId, stockId);
							//  成本表库存数量
							BigDecimal storeStockMaterialQuantity = storeStockMaterialService.getMaterialQuantityByStockID(materialId, stockId);
							Integer direction = -1;
							Date updateTime = new Date();
							// 库存更新
							try {
								storeStockMaterialService.updateMaterialWarehouse(storeStockMaterialQuantity,quantity,materialId,stockId,direction,updateTime,cost);
							} catch (Exception e) {
								throw new RuntimeException("库存主表更新失败");
							}
							//这个地方需要把采购申请的明细给减去
							BigDecimal receive_quantity = baseMapper.getpurchaseapplyDetailReciveNum(materialId,inNo);
							BigDecimal receQuantity = receive_quantity.subtract(quantity);
							// 这里需要更新采购明细红冲后的实际入库数量
							Integer integer = baseMapper.updateReceiveQuantity(receQuantity,materialId,inNo);
							if(integer != 1){
								return R.error("实际采购入库数量更新失败");
							}
							// 库存明细插入一条数据
							storeStockMaterialIoEntity.setTicketsNo(inNo);
							storeStockMaterialIoEntity.setMaterialId(materialId);
							storeStockMaterialIoEntity.setMaterialQuantity(quantity);
							storeStockMaterialIoEntity.setStockId(stockId);
							storeStockMaterialIoEntity.setType(StockMaterialIoTypeEnum.COUNTERACT.toInt());
							storeStockMaterialIoEntity.setDirection(direction);
							storeStockMaterialIoEntity.setCreateName(UserUtils.getCurentUser().getUsername());
							try {
								storeStockMaterialIoService.save(storeStockMaterialIoEntity);
							} catch (Exception e) {
								throw new RuntimeException("库存明细保存失败");
							}
						}
					}
					//查询采购入库的某个单号的所有
					List<StorePurchaseApplyDetailEntity> materialByinNo = storePurchaseApplyDetailService.getMaterialByinNo(inNo);
					// 查询当前要红冲的单号
					List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList1 = storeMaterialInDto.getStoreMaterialInDetailEntityList();
					for(int i = 0;i<storeMaterialInDetailEntityList1.size();i++){
						if(storeMaterialInDetailEntityList1.get(i).getMaterialQuantity().compareTo(materialByinNo.get(i).getMaterialQuantity()) == 1){
							return R.error("耗材ID：" + storeMaterialInDetailEntityList1.get(i).getMaterialId() + " 入库数量不能大于申请数量");
						}
						if (storeMaterialInDetailEntityList1.get(i).getMaterialQuantity().compareTo(BigDecimal.ZERO) == 0) {
							return R.error("耗材ID：" + storeMaterialInDetailEntityList1.get(i).getMaterialId() + " 的入库数量不能为0!");
						}
					}
					// 生成新的单据号 store_material_in
					String ss = "-";
					String newInNo = inNo+ss;
					String hcNewInNo;
					// 这里只是查询已经审核并且是红冲的的把它冲红掉
					Integer EnumTypeS = StockMaterialIoTypeEnum.COUNTERACT.toInt();
					List<StoreMaterialInEntity> storeMaterialListByState = storeMaterialInService.getStoreMaterialListByStateNoState(newInNo, EnumTypeS);
					if(storeMaterialListByState.size()>0){
						Integer i = storeMaterialListByState.size()+1;
						hcNewInNo = inNo+ss+i;
					}else{
						hcNewInNo = inNo+ss+1;
					}
					//     入库表  入库明细表   采购申请插入   采购申请明细插入
					storeMaterialInEntity.setInNo(hcNewInNo);
					BigDecimal StorematerialInEntityTotalMoney = null;
					for(int i = 0;i<storeMaterialInDto.getStoreMaterialInDetailEntityList().size();i++){
						if(i == 0){
							StorematerialInEntityTotalMoney = storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getUnitMoney().multiply(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getMaterialQuantity());
						}else{
							StorematerialInEntityTotalMoney = storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getUnitMoney().multiply(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getMaterialQuantity()).add(StorematerialInEntityTotalMoney);
						}
					}
					storeMaterialInEntity.setTotalMoney(StorematerialInEntityTotalMoney);
					storeMaterialInEntity.setCreateName(UserUtils.getCurentUser().getUsername());
					storeMaterialInEntity.setStockId(stockId);
					try {
						storeMaterialInService.save(storeMaterialInEntity);
					} catch (Exception e) {
						throw new RuntimeException("主表数据插入异常");
					}
					for(int i = 0;i<storeMaterialInDto.getStoreMaterialInDetailEntityList().size();i++){
						storeMaterialInDetailEntityes.setInNo(hcNewInNo);
						storeMaterialInDetailEntityes.setInId(storeMaterialInEntity.getInId());
						storeMaterialInDetailEntityes.setMaterialId(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getMaterialId());
						storeMaterialInDetailEntityes.setMaterialQuantity(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getMaterialQuantity());
						storeMaterialInDetailEntityes.setUnitMoney(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getUnitMoney());
						storeMaterialInDetailEntityes.setTotalMoney(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getUnitMoney().multiply(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getMaterialQuantity()));
						storeMaterialInDetailEntityes.setUnit(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getUnit());
						storeMaterialInDetailEntityes.setRemark(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(i).getRemark());
						storeMaterialInDetailEntityes.setCreateName(UserUtils.getCurentUser().getUsername());
						try {
							storeMaterialInDetailService.save(storeMaterialInDetailEntityes);
						} catch (Exception e) {
							throw new RuntimeException("明细表数据插入异常");
						}
					}
					return R.ok("操作完成");
				} else {
					return R.error("请确认是采购入库的并且已经审批");
				}
			}else{
				StoreMaterialInDetailEntity storeMaterialInDetailEntityes = new StoreMaterialInDetailEntity();
				Integer i = storeMaterialInEntitiesSix.size();
				String inNoNew = null;
				Integer inIdNew = null;
				Integer stockIdNew = null;

				for(int s = storeMaterialInEntitiesSix.size()-1;s< storeMaterialInEntitiesSix.size();s++){
					inNoNew = storeMaterialInEntitiesSix.get(s).getInNo();
					inIdNew = storeMaterialInEntitiesSix.get(s).getInId();
					stockIdNew = storeMaterialInEntitiesSix.get(s).getStockId();
				}
				List<StoreMaterialInDetailEntity> storeMaterialInDetailEntities = storeMaterialInDetailService.getInidAndInNo(inNoNew,inIdNew);
				for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntities) {
					String materialId = storeMaterialInDetailEntity.getMaterialId();
					// 入库数量
					BigDecimal quantity = storeMaterialInDetailEntity.getMaterialQuantity();
					// 获取对应的单价
					BigDecimal cost = storeStockMaterialService.getCost(materialId, stockIdNew);
					//  成本表库存数量
					BigDecimal storeStockMaterialQuantity = storeStockMaterialService.getMaterialQuantityByStockID(materialId, stockIdNew);
					Integer direction = -1;
					Date updateTime = new Date();
					// 库存更新
					try {
						storeStockMaterialService.updateMaterialWarehouse(storeStockMaterialQuantity,quantity,materialId,stockIdNew,direction,updateTime,cost);
					} catch (Exception e) {
						throw new RuntimeException("库存主表更新失败");
					}

					//这个地方需要把采购申请的明细给减去
					BigDecimal receive_quantity = baseMapper.getpurchaseapplyDetailReciveNum(materialId,inNo);
					BigDecimal receQuantity = receive_quantity.subtract(quantity);
					// 这里需要更新采购明细红冲后的实际入库数量
					Integer integer = baseMapper.updateReceiveQuantity(receQuantity,materialId,inNo);
					if(integer != 1){
						return R.error("实际采购入库数量更新失败");
					}

					// 库存明细插入一条数据
					storeStockMaterialIoEntity.setTicketsNo(inNo);
					storeStockMaterialIoEntity.setMaterialId(materialId);
					storeStockMaterialIoEntity.setMaterialQuantity(quantity);
					storeStockMaterialIoEntity.setStockId(stockIdNew);
					storeStockMaterialIoEntity.setType(StockMaterialIoTypeEnum.COUNTERACT.toInt());
					storeStockMaterialIoEntity.setDirection(direction);
					storeStockMaterialIoEntity.setCreateName(UserUtils.getCurentUser().getUsername());
					try {
						storeStockMaterialIoService.save(storeStockMaterialIoEntity);
					} catch (Exception e) {
						throw new RuntimeException("库存明细保存失败");
					}
				}
				//查询采购入库的某个单号的所有
				List<StorePurchaseApplyDetailEntity> materialByinNo = storePurchaseApplyDetailService.getMaterialByinNo(inNo);
				// 查询当前要红冲的单号
				List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList1 = storeMaterialInDto.getStoreMaterialInDetailEntityList();
				for(int ss = 0;ss<storeMaterialInDetailEntityList1.size();ss++){
					if(storeMaterialInDetailEntityList1.get(ss).getMaterialQuantity().compareTo(materialByinNo.get(ss).getMaterialQuantity()) == 1){
						return R.error("耗材ID：" + storeMaterialInDetailEntityList1.get(ss).getMaterialId() + " 入库数量不能大于申请数量");
					}
					if (storeMaterialInDetailEntityList1.get(ss).getMaterialQuantity().compareTo(BigDecimal.ZERO) == 0) {
						return R.error("耗材ID：" + storeMaterialInDetailEntityList1.get(ss).getMaterialId() + " 的入库数量不能为0!");
					}
				}

				// 生成新的单据号 store_material_in
				String ss = "-";
				String newInNo = inNo+ss;
				String hcNewInNo;
				// 这里只是查询已经审核并且是红冲的的把它冲红掉
				Integer EnumTypeS = StockMaterialIoTypeEnum.COUNTERACT.toInt();
				List<StoreMaterialInEntity> storeMaterialListByState = storeMaterialInService.getStoreMaterialListByStateNoState(newInNo, EnumTypeS);
				if(storeMaterialListByState.size()>0){
					Integer m = storeMaterialListByState.size()+1;
					hcNewInNo = inNo+ss+m;
				}else{
					hcNewInNo = inNo+ss+1;
				}
				//     入库表  入库明细表   采购申请插入   采购申请明细插入
				storeMaterialInEntity.setInNo(hcNewInNo);
				BigDecimal StorematerialInEntityTotalMoney = null;
				for(int z = 0;z<storeMaterialInDto.getStoreMaterialInDetailEntityList().size();z++){
					if(z == 0){
						StorematerialInEntityTotalMoney = storeMaterialInDto.getStoreMaterialInDetailEntityList().get(z).getUnitMoney().multiply(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(z).getMaterialQuantity());
					}else{
						StorematerialInEntityTotalMoney = storeMaterialInDto.getStoreMaterialInDetailEntityList().get(z).getUnitMoney().multiply(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(z).getMaterialQuantity()).add(StorematerialInEntityTotalMoney);
					}
				}
				storeMaterialInEntity.setTotalMoney(StorematerialInEntityTotalMoney);
				storeMaterialInEntity.setCreateName(UserUtils.getCurentUser().getUsername());
				storeMaterialInEntity.setStockId(stockIdNew);
				try {
					storeMaterialInService.save(storeMaterialInEntity);
				} catch (Exception e) {
					throw new RuntimeException("主表数据插入异常");
				}
				for(int b = 0;b<storeMaterialInDto.getStoreMaterialInDetailEntityList().size();b++){
					storeMaterialInDetailEntityes.setInNo(hcNewInNo);
					storeMaterialInDetailEntityes.setInId(storeMaterialInEntity.getInId());
					storeMaterialInDetailEntityes.setMaterialId(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getMaterialId());
					storeMaterialInDetailEntityes.setMaterialQuantity(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getMaterialQuantity());
					storeMaterialInDetailEntityes.setUnitMoney(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getUnitMoney());
					storeMaterialInDetailEntityes.setTotalMoney(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getUnitMoney().multiply(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getMaterialQuantity()));
					storeMaterialInDetailEntityes.setUnit(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getUnit());
					storeMaterialInDetailEntityes.setRemark(storeMaterialInDto.getStoreMaterialInDetailEntityList().get(b).getRemark());
					storeMaterialInDetailEntityes.setCreateName(UserUtils.getCurentUser().getUsername());
					try {
						storeMaterialInDetailService.save(storeMaterialInDetailEntityes);
					} catch (Exception e) {
						throw new RuntimeException("明细表数据插入异常");
					}
				}
				return R.ok("操作完成");
			}
		}
		return R.error("无数据");
	}

	/**
	 * 入库审核
	 *
	 * @param id
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R audit (Integer id){
		//仓库
		ErpStockEntity erpStockEntity = baseMapper.getStockBySellerId(UserUtils.getCurentUser().getSellerId(), 1);
		/************ 1.入库单变动 start ************/
		StoreMaterialInEntity storeMaterialInEntity = baseMapper.selectById(id);
		if (storeMaterialInEntity == null || storeMaterialInEntity.getStatus() != StoreMaterialInStatusEnum.WAIT_AUDIT.toInt()) {
			return R.error("入库单不是待审核状态，审核失败！");
		}
		Map<String, Object> updatestoreMaterialInMap = new HashMap<>();
		updatestoreMaterialInMap.put("status", StoreMaterialInStatusEnum.AUDIT.toInt());
		updatestoreMaterialInMap.put("checkName", UserUtils.getCurentUser().getUsername());
		updatestoreMaterialInMap.put("checkTime", new Date());
		baseMapper.updateByMap(updatestoreMaterialInMap, storeMaterialInEntity.getInId());
		/************ 1.入库单变动 end ************/

		/************ 2.采购单变动 start ************/
		// 入库类型
		Integer type = storeMaterialInEntity.getType();
		if (type.intValue() == StockMaterialIoTypeEnum.PUCHASE_IN.toInt()) { // 采购入库
			// 采购申请单
			StorePurchaseApplyEntity storePurchaseApplyEntity = baseMapper.getPurchaseApplyByNo(storeMaterialInEntity.getInNo());
			// 采购申请是否完结
			boolean purchaseApplyfinish = true;
			Map<String, Object> purchaseApplyMap = new HashMap<>();
			purchaseApplyMap.put("receiveName", UserUtils.getCurentUser().getUsername());
			purchaseApplyMap.put("receive_time", new Date());

			List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = storeMaterialInDetailService.list(
					new QueryWrapper<StoreMaterialInDetailEntity>()
							.eq("in_id", id)
							.eq("`del`", DeleteEnum.NOT_DELETE.toInt())
			);
			for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntityList) {
				StorePurchaseApplyDetailEntity purchaseApplyDetail = baseMapper.getPurchaseApplyDetail(storeMaterialInEntity.getInNo()
						, storeMaterialInDetailEntity.getMaterialId());
				// 表示可以上多少
				BigDecimal UseQuantity = purchaseApplyDetail.getMaterialQuantity().subtract(purchaseApplyDetail.getReceiveQuantity());
				if(UseQuantity.compareTo(storeMaterialInDetailEntity.getMaterialQuantity()) == -1){
					throw new RuntimeException("入库数量大于实际采购申请数量剩余数量");
				}
				if(UseQuantity.compareTo(BigDecimal.ZERO) == 0){
					throw new RuntimeException("该单号下的物料已经全部入完库,不允许再入库");
				}
				Map<String, Object> updateMap = new HashMap<>();
				updateMap.put("receiveQuantity", storeMaterialInDetailEntity.getMaterialQuantity().doubleValue());

				// 入库数量
				BigDecimal num = purchaseApplyDetail.getReceiveQuantity();
				num = num.add(storeMaterialInDetailEntity.getMaterialQuantity());
				if (num.doubleValue() == purchaseApplyDetail.getMaterialQuantity().doubleValue()) {
					updateMap.put("status", 3);
				} else {
					purchaseApplyfinish = false;
				}
				Integer applydetailId = purchaseApplyDetail.getApplyDetailId();
				updateMap.put("receiveQuantity",num);
				baseMapper.updatePurchaseApplyDetail(updateMap, applydetailId);
				/************ 3.库存变动 start ************/
				StoreStockMaterialEntity storeStockMaterialEntity = storeStockMaterialService.getStockMaterial(
						storeMaterialInDetailEntity.getMaterialId(), UserUtils.getCurentUser().getSellerId());
				if (storeStockMaterialEntity == null) {
					storeStockMaterialEntity = new StoreStockMaterialEntity();
					storeStockMaterialEntity.setStockId(erpStockEntity.getStockId());
					storeStockMaterialEntity.setMaterialId(storeMaterialInDetailEntity.getMaterialId());
					storeStockMaterialEntity.setMaterialQuantity(storeMaterialInDetailEntity.getMaterialQuantity());
					storeStockMaterialEntity.setCost(storeMaterialInDetailEntity.getUnitMoney());
					storeStockMaterialEntity.setMoney(storeMaterialInDetailEntity.getTotalMoney());
					storeStockMaterialEntity.setUnit(storeMaterialInDetailEntity.getUnit());
					storeStockMaterialEntity.setRemark("采购初次生产耗材信息");
					storeStockMaterialEntity.setCreateName(UserUtils.getCurentUser().getUsername());
					storeStockMaterialService.save(storeStockMaterialEntity);
					ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
					erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
					erpStockLogEntity.setType(1);
					erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
					erpStockLogEntity.setLogText("采购入库审核");
					erpStockLogService.saveBatch(erpStockLogEntity);

				} else {
					BigDecimal quantity = storeMaterialInDetailEntity.getMaterialQuantity();

					BigDecimal	Cost = baseMapper.getCostByMaterialId(storeStockMaterialEntity.getMaterialId(),storeStockMaterialEntity.getStockId());

					if(Cost == null){
						Cost = baseMapper.getCostByMaterialIdAndApplyNo(storeMaterialInEntity.getInNo(),storeStockMaterialEntity.getMaterialId());
					}
					try {
						baseMapper.updateCostToStoreStockMaterial(Cost, storeStockMaterialEntity.getMaterialId(), storeStockMaterialEntity.getStockId());
					} catch (Exception e) {
						throw new RuntimeException("成本维护失败");
					}
					String materialId = storeStockMaterialEntity.getMaterialId();
					// 获取对应仓库ID
					Integer stockID = storeStockMaterialEntity.getStockId();

					// 新增入库的总金额
					BigDecimal money = null;
					try {
						money = Cost.multiply(quantity);
					} catch (Exception e) {
						throw new RuntimeException("请维护当前物料ID基础数据");
					}
					Integer integer = storeStockMaterialService.updateMaterialInfo(quantity, money, materialId,stockID);

					if (integer != 1) {
						throw new RuntimeException("库存更新失败");
					}
				}
				// 库存交易明细
				StoreStockMaterialIoEntity storeStockMaterialIoEntity = new StoreStockMaterialIoEntity();
				storeStockMaterialIoEntity.setTicketsNo(storeMaterialInDetailEntity.getInNo());
				storeStockMaterialIoEntity.setMaterialId(storeMaterialInDetailEntity.getMaterialId());
				storeStockMaterialIoEntity.setMaterialQuantity(storeMaterialInDetailEntity.getMaterialQuantity());
				storeStockMaterialIoEntity.setUnit(storeMaterialInDetailEntity.getUnit());
				storeStockMaterialIoEntity.setStockId(erpStockEntity.getStockId());
				storeStockMaterialIoEntity.setType(storeMaterialInEntity.getType());
				storeStockMaterialIoEntity.setDirection(storeMaterialInEntity.getDirection());
				storeStockMaterialIoEntity.setCreateName(UserUtils.getCurentUser().getUsername());
				storeStockMaterialIoService.save(storeStockMaterialIoEntity);
				/************ 3.库存变动 end ************/
			}
			if (purchaseApplyfinish) {
				purchaseApplyMap.put("status", 3);
				//入库完结
				purchaseApplyMap.put("receiveTime",new Date());
			}
			Integer applyId = storePurchaseApplyEntity.getApplyId();
			baseMapper.updatePurchaseApply(purchaseApplyMap, applyId);
			ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
			erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
			erpStockLogEntity.setType(1);
			erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
			erpStockLogEntity.setLogText("采购入库审核");
			erpStockLogService.saveBatch(erpStockLogEntity);
		} else if (type.intValue() == StockMaterialIoTypeEnum.ALLOT_IN.toInt()) {

			int in_id = id;

			List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = storeMaterialInDetailService.list(new QueryWrapper<StoreMaterialInDetailEntity>().eq("in_id", in_id).eq("del", DeleteEnum.NOT_DELETE.toInt()));

			for (StoreMaterialInDetailEntity storeMaterialinDetailEntity : storeMaterialInDetailEntityList) {
				StoreMaterialInDetailEntity baseMapperOutMaterialDetail = baseMapper.getOutMaterialDetail(storeMaterialinDetailEntity.getInNo(), storeMaterialinDetailEntity.getMaterialId(),storeMaterialinDetailEntity.getInId());
				Map<String, Object> updateMap = new HashMap<>();
				updateMap.put("OutWareHouseQuantity", storeMaterialinDetailEntity.getMaterialQuantity().doubleValue());
				BigDecimal num = storeMaterialinDetailEntity.getMaterialQuantity();
				num.add(storeMaterialinDetailEntity.getMaterialQuantity());
				try {
					// 更新操作主表库存和总金额
					String materialId = baseMapperOutMaterialDetail.getMaterialId();
					// 获取 Store_stock_material  当前商品的库存数量
					Integer stockId = storeMaterialInEntity.getStockId();
					// 需要增加的
					BigDecimal quantity = baseMapperOutMaterialDetail.getMaterialQuantity();
					// 单价
					BigDecimal price = baseMapperOutMaterialDetail.getUnitMoney();
					// 更新 Store_stock_material
					storeStockMaterialService.updateQuantityByMaterialId(materialId,quantity, price,stockId);
					//  主表明细添加数据
					StoreStockMaterialIoEntity storeStockMaterialIoEntity = new StoreStockMaterialIoEntity();
					storeStockMaterialIoEntity.setTicketsNo(storeMaterialinDetailEntity.getInNo());
					storeStockMaterialIoEntity.setMaterialId(storeMaterialinDetailEntity.getMaterialId());
					storeStockMaterialIoEntity.setMaterialQuantity(quantity);
					storeStockMaterialIoEntity.setUnit(storeMaterialinDetailEntity.getUnit());
					storeStockMaterialIoEntity.setType(storeMaterialInEntity.getType());
					storeStockMaterialIoEntity.setDirection(DirectionEnum.INCREASE.toInt());
					storeStockMaterialIoEntity.setStockId(erpStockEntity.getStockId());
					storeStockMaterialIoEntity.setCreateName(UserUtils.getCurentUser().getUsername());
					storeStockMaterialIoService.save(storeStockMaterialIoEntity);
				} catch (Exception e) {
					throw new RuntimeException("库存更新失败");
				}
			}
			ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
			erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
			erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
			erpStockLogEntity.setType(2);
			erpStockLogEntity.setLogText("调拨入库审核操作");
			erpStockLogService.saveBatch(erpStockLogEntity);
		}else if(type.intValue() == StockMaterialIoTypeEnum.COUNTERACT.toInt()){
			int in_id = id;
			List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = storeMaterialInDetailService.list(new QueryWrapper<StoreMaterialInDetailEntity>().eq("in_id", in_id).eq("del", DeleteEnum.NOT_DELETE.toInt()));
			StoreStockMaterialIoEntity storeStockMaterialIoEntity = new StoreStockMaterialIoEntity();
			String apply_NO = null;
			for(int e =storeMaterialInDetailEntityList.size()-1;e < storeMaterialInDetailEntityList.size();e++ ){
				apply_NO = storeMaterialInDetailEntityList.get(e).getInNo();
			}
			// 采购申请是否完结
			boolean purchaseApplyfinish = true;
			try {
				for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntityList) {
					StoreMaterialInDetailEntity baseMapperOutMaterialDetail = baseMapper.getOutMaterialDetail(storeMaterialInDetailEntity.getInNo(), storeMaterialInDetailEntity.getMaterialId(), storeMaterialInDetailEntity.getInId());
					Integer stockId = erpStockEntity.getStockId();
					String materialId = baseMapperOutMaterialDetail.getMaterialId();
					BigDecimal quantity = baseMapperOutMaterialDetail.getMaterialQuantity();
					BigDecimal totalMoney = baseMapperOutMaterialDetail.getTotalMoney();
					Integer integer = baseMapper.updateStoreStockMaterial(stockId, materialId,quantity,totalMoney);
					if (integer != 1) {
						throw new RuntimeException("成本更新失败");
					}
					storeStockMaterialIoEntity.setTicketsNo(storeMaterialInDetailEntity.getInNo());
					storeStockMaterialIoEntity.setMaterialId(storeMaterialInDetailEntity.getMaterialId());
					storeStockMaterialIoEntity.setMaterialQuantity(quantity);
					storeStockMaterialIoEntity.setUnit(storeMaterialInDetailEntity.getUnit());
					storeStockMaterialIoEntity.setType(storeMaterialInEntity.getType());
					storeStockMaterialIoEntity.setDirection(DirectionEnum.INCREASE.toInt());
					storeStockMaterialIoEntity.setStockId(erpStockEntity.getStockId());
					storeStockMaterialIoEntity.setCreateName(UserUtils.getCurentUser().getUsername());
					storeStockMaterialIoService.save(storeStockMaterialIoEntity);
					String applyNO = storeStockMaterialIoEntity.getTicketsNo();
					applyNO = applyNO.substring(0,13);
					String materialID = storeStockMaterialIoEntity.getMaterialId();
					// 目前实际采购入库了多少
					BigDecimal receiveQuantity = storePurchaseApplyDetailService.getReceiveQuantity(applyNO, materialID);
					BigDecimal quantityRecive = receiveQuantity.add(storeStockMaterialIoEntity.getMaterialQuantity());
					storePurchaseApplyDetailService.updateReceiveQuantity(quantityRecive, applyNO, materialID);
					// 采购申请的数量
					BigDecimal materialQuantity = storePurchaseApplyDetailService.getMaterialQuantity(applyNO, materialID);
					if(materialQuantity.compareTo(quantityRecive) != 0){
						purchaseApplyfinish = false;
					}
				}
			}catch (Exception e){
				throw new RuntimeException("审核失败");
			}finally {
				// 这里是要回设采购申请是否入完库
				if(purchaseApplyfinish){
					int status = 3;
					apply_NO = apply_NO.substring(0,13);
					Integer integer = baseMapper.updateStorePurchaseApplyStatus(apply_NO, status);
					if(integer == 0){
						throw new RuntimeException("采购申请状态回设失败");
					}
				}
			}
		}else if (type.intValue() == StockMaterialIoTypeEnum.TAKE_INVENTORY.toInt()){
			//盘存
			//storeMaterialInEntity入库信息实体类
			//获得仓库id
			Integer stockId = storeMaterialInEntity.getStockId();
			//每一个耗材信息都会更新成本store_stock_material,并向store_stock_material_io插入记录
			List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = storeMaterialInDetailService.list(new QueryWrapper<StoreMaterialInDetailEntity>()
					.eq("in_id", storeMaterialInEntity.getInId()).eq("del", DeleteEnum.NOT_DELETE.toInt()));
			if(storeMaterialInDetailEntityList == null || storeMaterialInDetailEntityList.size() == 0)throw new RRException("未查询到耗材详细信息,盘存审核失败");
			for (StoreMaterialInDetailEntity storeMaterialInDetailEntity : storeMaterialInDetailEntityList) {
				//获得入库明细表上的耗材id/数量
				String materialId = storeMaterialInDetailEntity.getMaterialId();
				BigDecimal materialQuantity = storeMaterialInDetailEntity.getMaterialQuantity();
				//查询仓库当前耗材信息
				List<StoreStockMaterialEntity> storeStockMaterialEntityList = storeStockMaterialService.list(new QueryWrapper<StoreStockMaterialEntity>().eq("stock_id", stockId).eq("material_id", materialId)
						.eq("del", DeleteEnum.NOT_DELETE.toInt()));
				if(storeStockMaterialEntityList != null && storeStockMaterialEntityList.size() > 0){
					if(storeStockMaterialEntityList.size() == 1){
						//更新盘存信息
						Integer status = storeStockMaterialService.updateTIStoreStock(materialQuantity,stockId,materialId);
						if(status != 1){
							throw new RRException("盘存审核更新库存异常");
						}
						//在并向store_stock_material_io插入记录做记录
						StoreStockMaterialIoEntity storeStockMaterialIoEntity = new StoreStockMaterialIoEntity();
						storeStockMaterialIoEntity.setTicketsNo(storeMaterialInDetailEntity.getInNo());
						storeStockMaterialIoEntity.setMaterialId(storeMaterialInDetailEntity.getMaterialId());
						storeStockMaterialIoEntity.setMaterialQuantity(storeMaterialInDetailEntity.getMaterialQuantity());
						storeStockMaterialIoEntity.setUnit(storeMaterialInDetailEntity.getUnit());
						storeStockMaterialIoEntity.setType(storeMaterialInEntity.getType());
						storeStockMaterialIoEntity.setDirection(DirectionEnum.INCREASE.toInt());
						storeStockMaterialIoEntity.setStockId(stockId);
						storeStockMaterialIoEntity.setCreateName(UserUtils.getCurentUser().getUsername());
						storeStockMaterialIoService.save(storeStockMaterialIoEntity);
						ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
						erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
						erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
						erpStockLogEntity.setType(4);
						erpStockLogEntity.setLogText("盘存审核日志记录");
						erpStockLogService.saveBatch(erpStockLogEntity);
					}else{
						throw new RRException("当前门店匹配到多个耗材信息,耗材id:"+ materialId +",盘存审核失败");
					}
				}else{
					throw new RRException("未匹配到耗材id:"+ materialId +",盘存审核失败");
				}
			}
		}
		/************ 2.采购单变动 end ************/
		return R.ok("操作完成");
	}

	@Override
	public R reject (Integer id){
		StoreMaterialInEntity storeMaterialInEntity = baseMapper.selectById(id);
		if (storeMaterialInEntity == null || storeMaterialInEntity.getStatus() != StoreMaterialInStatusEnum.WAIT_AUDIT.toInt()) {
			return R.error("入库单不是待审核状态，驳回失败！");
		}
		if(storeMaterialInEntity.getType().intValue() == 1){
			Map<String, Object> updatestoreMaterialInMap = new HashMap<>();
			updatestoreMaterialInMap.put("status", StoreMaterialInStatusEnum.REFUCE.toInt());
			updatestoreMaterialInMap.put("checkName", UserUtils.getCurentUser().getUsername());
			updatestoreMaterialInMap.put("checkTime", new Date());
			baseMapper.updateByMap(updatestoreMaterialInMap, storeMaterialInEntity.getInId());
			ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
			erpStockLogEntity.setLogText("采购入库未审核采取驳回操作");
			erpStockLogEntity.setType(1);
			erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
			erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
			erpStockLogService.saveBatch(erpStockLogEntity);
			return R.ok("操作完成");
		}else if(storeMaterialInEntity.getType().intValue() == 7){
			Map<String, Object> updatestoreMaterialInMap = new HashMap<>();
			updatestoreMaterialInMap.put("status", StoreMaterialInStatusEnum.REFUCE.toInt());
			updatestoreMaterialInMap.put("checkName", UserUtils.getCurentUser().getUsername());
			updatestoreMaterialInMap.put("checkTime", new Date());
			baseMapper.updateByMap(updatestoreMaterialInMap, storeMaterialInEntity.getInId());
			ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
			erpStockLogEntity.setLogText("调拨入库未审核采取驳回操作");
			erpStockLogEntity.setType(2);
			erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
			erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
			erpStockLogService.saveBatch(erpStockLogEntity);
			return R.ok("操作完成");
		}else if (storeMaterialInEntity.getType().intValue() == StockMaterialIoTypeEnum.TAKE_INVENTORY.toInt()){
			//盘存
			Map<String, Object> updateStoreMaterialInMap = New.hashMap();
			updateStoreMaterialInMap.put("status", StoreMaterialInStatusEnum.REFUCE.toInt());
			updateStoreMaterialInMap.put("checkName", UserUtils.getCurentUser().getUsername());
			updateStoreMaterialInMap.put("checkTime", new Date());
			baseMapper.updateByMap(updateStoreMaterialInMap,storeMaterialInEntity.getInId());
			ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
			erpStockLogEntity.setLogText("盘存未审核驳回操作");
			erpStockLogEntity.setType(4);
			erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
			erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
			erpStockLogService.saveBatch(erpStockLogEntity);
			return R.ok("操作完成");
		}
		return R.error("库存交易类型异常");
	}

	@Override
	public List<StoreMaterialInEntity> getStoreMaterialList (String inNo){
		return baseMapper.getStoreMaterialInList(inNo);
	}

	@Override
	public List<StoreMaterialInEntity> getStoreMaterialListByState (String inNo,Integer EnumType){
		return baseMapper.getStoreMaterialInListByStatus(inNo,EnumType);
	}

	@Override
	public List<StoreMaterialInEntity> getStoreMaterialListByEnumTypes(String inNo, Integer EnumTypes) {
		return baseMapper.getStoreMaterialListByEnumTypes(inNo,EnumTypes);
	}

	@Override
	public List<StoreMaterialInEntity> getStoreMaterialListByStateNoState(String inNo, Integer EnumTypeS) {
		return baseMapper.getStoreMaterialInListByStatusNoState(inNo,EnumTypeS);
	}

	@Override
	public BigDecimal getTotalMoney(String inNo) {
		return baseMapper.getTotalMoney(inNo);
	}

	/**
	 * 盘存
	 * @param storePurchaseApplyDto
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R inventory(StorePurchaseApplyDto storePurchaseApplyDto,SysUserEntity userEntity) {
		StoreMaterialInEntity storeMaterialInEntity = handlerDtoGetStoreMaterialIn(storePurchaseApplyDto,userEntity);
		this.baseMapper.insert(storeMaterialInEntity);
		List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = handlerDtoGetStoreMaterialInDetailList(storePurchaseApplyDto,storeMaterialInEntity);
		storeMaterialInDetailService.saveBatch(storeMaterialInDetailEntityList);
		//盘存申请日志记录
		ErpStockLogEntity erpStockLogEntity = new ErpStockLogEntity();
		erpStockLogEntity.setBillNo(storeMaterialInEntity.getInNo());
		erpStockLogEntity.setCreateName(UserUtils.getCurentUser().getUsername());
		erpStockLogEntity.setType(4);
		erpStockLogEntity.setLogText("盘存申请日志记录");
		erpStockLogService.saveBatch(erpStockLogEntity);
		return R.ok();
	}

	@Override
	public Integer getStockByInId(Integer inId) {
		return baseMapper.getStockByInId(inId);
	}

	@Override
	public StoreMaterialInEntity getInfoData(Integer inId) {
		return baseMapper.getInfoData(inId);
	}

	@Override
	public String getInNoByinId(Integer inId) {
		return baseMapper.getInNoByinId(inId);
	}

	@Override
	public List<StoreMaterialInEntity> getAlreadyInAndState(String inNo) {
		return baseMapper.getAlreadyInAndState(inNo);
	}


	/**
	 * 单据图片修改
	 * @param inId
	 * @param ids
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R editOtherAccessory(Integer inId, String ids) {
		Integer status = baseMapper.saveOtherAccessory(inId,ids);
		if(status == 1){
			return R.ok();
		}else{
			throw new RRException("修改单据号出现异常,修改入库单据数量:"+status);
		}
	}

	/**
	 * 处理dto返回List<StoreMaterialInDetailEntity>
	 * @param storePurchaseApplyDto
	 * @return
	 */
	private List<StoreMaterialInDetailEntity> handlerDtoGetStoreMaterialInDetailList(StorePurchaseApplyDto storePurchaseApplyDto,StoreMaterialInEntity storeMaterialInEntity) {
		List<StorePurchaseApplyDetailEntity> storePurchaseApplyDetailEntityList = storePurchaseApplyDto.getStorePurchaseApplyDetailEntityList();
		List<StoreMaterialInDetailEntity> storeMaterialInDetailEntityList = New.arrayList();
		if(storePurchaseApplyDetailEntityList != null && storePurchaseApplyDetailEntityList.size() > 0){
			for(int i = 0;i<storePurchaseApplyDetailEntityList.size();i++){
				StorePurchaseApplyDetailEntity storePurchaseApplyDetailEntity = storePurchaseApplyDetailEntityList.get(i);
				StoreMaterialInDetailEntity storeMaterialInDetailEntity = new StoreMaterialInDetailEntity();
				storeMaterialInDetailEntity.setInId(storeMaterialInEntity.getInId());
				storeMaterialInDetailEntity.setInNo(storeMaterialInEntity.getInNo());
				storeMaterialInDetailEntity.setMaterialId(storePurchaseApplyDetailEntity.getMaterialId());
				storeMaterialInDetailEntity.setMaterialQuantity(storePurchaseApplyDetailEntity.getMaterialQuantity());
				storeMaterialInDetailEntity.setUnitMoney(storePurchaseApplyDetailEntity.getUnitMoney());
				storeMaterialInDetailEntity.setTotalMoney(storePurchaseApplyDetailEntity.getTotalMoney());
				storeMaterialInDetailEntity.setUnit(storePurchaseApplyDetailEntity.getUnit());
				storeMaterialInDetailEntity.setRemark(storeMaterialInEntity.getRemark());
				storeMaterialInDetailEntity.setCreateName(storeMaterialInEntity.getCreateName());
				storeMaterialInDetailEntityList.add(storeMaterialInDetailEntity);
			}
		}else{
			throw new RRException("异常申请,耗材信息为空!");
		}
		return storeMaterialInDetailEntityList;
	}

	/**
	 * 处理前端dto返回StoreMaterialInEntity
	 * @param storePurchaseApplyDto
	 * @param userEntity
	 * @return
	 */
	private StoreMaterialInEntity handlerDtoGetStoreMaterialIn(StorePurchaseApplyDto storePurchaseApplyDto ,SysUserEntity userEntity) {
		@NotNull StorePurchaseApplyEntity storePurchaseApplyEntity = storePurchaseApplyDto.getStorePurchaseApplyEntity();
		StoreMaterialInEntity storeMaterialInEntity = new StoreMaterialInEntity();
		String purchaseApplyNo = getPurchaseApplyNo(userEntity.getSellerId());
		storeMaterialInEntity.setInNo(purchaseApplyNo);
		storeMaterialInEntity.setTotalMoney(storePurchaseApplyEntity.getTotalMoney());
		storeMaterialInEntity.setTax(storePurchaseApplyEntity.getTax());
		//找到仓库id
//		ErpStockEntity erpStockEntity = null;
//		try{
//			erpStockEntity = erpStockService.getOne(new QueryWrapper<ErpStockEntity>().eq("institution", userEntity.getSellerId()).eq("type", 1));
//		}catch (Exception e){
//
//		}
		ErpStockEntity erpStockEntity = materialService.getLoginErpStock(userEntity.getSellerId());
		if(erpStockEntity == null){
			throw new RRException("登录人找不到生产仓库!");
		}
		storeMaterialInEntity.setStockId(erpStockEntity.getStockId());
		storeMaterialInEntity.setType(3);
		storeMaterialInEntity.setDirection(1);
		storeMaterialInEntity.setStatus(1);
		storeMaterialInEntity.setRemark(storePurchaseApplyEntity.getApplyRemark());
		storeMaterialInEntity.setCreateName(userEntity.getUsername());
		return storeMaterialInEntity;
	}

	private String AutoNo(Long sellerId) {
		StringBuffer purchaseApplyNo = new StringBuffer("TI");
		if(sellerId < 10){
			purchaseApplyNo.append(0).append(sellerId);
		}else{
			purchaseApplyNo.append(sellerId);
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
		String formatStr =dateFormat.format(new Date());
		purchaseApplyNo.append(formatStr);

		//随机数
		int one = (int)(Math.random()*10);
		int two = (int)(Math.random()*10);
		int three = (int)(Math.random()*10);
		purchaseApplyNo.append(one).append(two).append(three);
		return purchaseApplyNo.toString();
	}

	private String getPurchaseApplyNo(Long sellerId){
		//判断采购申请单号是否重复
		String purchaseApplyNo = AutoNo(sellerId);
		boolean isRepeat = false;
		List<StoreMaterialInEntity> storeMaterialInEntityList = this.baseMapper.selectList(
				new QueryWrapper<StoreMaterialInEntity>().eq("in_no",purchaseApplyNo)
		);
		do {

			if(storeMaterialInEntityList != null && storeMaterialInEntityList.size() > 0){
				isRepeat = true;
				purchaseApplyNo = AutoNo(sellerId);
			}else{
				isRepeat = false;
			}
		}while (isRepeat);
		return purchaseApplyNo;
	}
}
